{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<a href=\"https://colab.research.google.com/drive/1oRHJGDS9lT1MteXfwHa3UpXhixwNOGle?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>"
      ],
      "metadata": {
        "id": "wTTXfmmeB0hw"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Least-to-Most Prompting"
      ],
      "metadata": {
        "id": "AKyaIHK-a8y9"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "oKCjKC3G7z9R"
      },
      "outputs": [],
      "source": [
        "!pip install -qU google-generativeai"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import google.generativeai as genai\n",
        "import getpass"
      ],
      "metadata": {
        "id": "FDWBbZo8bBSZ"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Get free-tier Google's Gemini API Key here: https://aistudio.google.com/app/apikey"
      ],
      "metadata": {
        "id": "rENZcvV5bJMG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "API_KEY = getpass.getpass(\"Enter your Google API key: \")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "JZzPH4GvbN7W",
        "outputId": "4366fb70-8aef-4c24-eeb7-3ff4831b0e0e"
      },
      "execution_count": 3,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Enter your Google API key: ··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "genai.configure(api_key=API_KEY)"
      ],
      "metadata": {
        "id": "vwo51NLlbTBO"
      },
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class LeastToMostAgent:\n",
        "    def __init__(self):\n",
        "        self.model = genai.GenerativeModel(\"gemini-2.0-flash\")\n",
        "        self.solution_chain = []\n",
        "\n",
        "    def decompose_problem(self, problem):\n",
        "        \"\"\"Step 1: Break into sub-problems from easiest to hardest\"\"\"\n",
        "        prompt = f\"\"\"Break down this problem into sub-problems, ordered from EASIEST to HARDEST.\n",
        "        Each sub-problem should build on previous ones.\n",
        "\n",
        "        Problem: {problem}\n",
        "\n",
        "        List 3-6 sub-problems in order of increasing difficulty:\"\"\"\n",
        "\n",
        "        response = self.model.generate_content(prompt).text\n",
        "\n",
        "        # Parse sub-problems\n",
        "        subproblems = []\n",
        "        for line in response.split(\"\\n\"):\n",
        "            line = line.strip()\n",
        "            if line and (line[0].isdigit() or line.startswith(\"-\")):\n",
        "                subproblem = line.lstrip(\"0123456789.-) \").strip()\n",
        "                if subproblem and len(subproblem) > 10:\n",
        "                    subproblems.append(subproblem)\n",
        "\n",
        "        return subproblems\n",
        "\n",
        "    def solve_subproblem(self, subproblem, previous_solutions):\n",
        "        \"\"\"Step 2-3: Solve sub-problem using previous solutions\"\"\"\n",
        "        if previous_solutions:\n",
        "            context = \"\\n\\n\".join([\n",
        "                f\"Previous Solution {i+1}:\\nProblem: {prev_prob}\\nSolution: {prev_sol}\"\n",
        "                for i, (prev_prob, prev_sol) in enumerate(previous_solutions)\n",
        "            ])\n",
        "\n",
        "            prompt = f\"\"\"You have solved these simpler problems:\n",
        "\n",
        "            {context}\n",
        "\n",
        "            Now solve this next problem, building on what you learned:\n",
        "\n",
        "            Problem: {subproblem}\n",
        "\n",
        "            Solution:\"\"\"\n",
        "        else:\n",
        "            # First problem - no previous context\n",
        "            prompt = f\"\"\"Solve this problem (the easiest/foundational one):\n",
        "\n",
        "            Problem: {subproblem}\n",
        "\n",
        "            Solution:\"\"\"\n",
        "\n",
        "        response = self.model.generate_content(prompt).text\n",
        "        return response.strip()\n",
        "\n",
        "    def integrate_final_solution(self, original_problem, solution_chain):\n",
        "        \"\"\"Step 4: Combine all solutions into final answer\"\"\"\n",
        "        chain_text = \"\\n\\n\".join([\n",
        "            f\"Step {i+1}: {subprob}\\nSolution: {solution}\"\n",
        "            for i, (subprob, solution) in enumerate(solution_chain)\n",
        "        ])\n",
        "\n",
        "        prompt = f\"\"\"Original Problem: {original_problem}\n",
        "\n",
        "        Progressive Solutions (from easiest to hardest):\n",
        "        {chain_text}\n",
        "\n",
        "        Using all these progressive solutions, provide the complete final answer:\"\"\"\n",
        "\n",
        "        response = self.model.generate_content(prompt).text\n",
        "        return response.strip()\n",
        "\n",
        "    def solve(self, problem):\n",
        "        \"\"\"Main least-to-most prompting pipeline\"\"\"\n",
        "        print(f\"\\n{'='*60}\")\n",
        "        print(f\"📈 Least-to-Most Prompting\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"Problem: {problem}\\n\")\n",
        "\n",
        "        # Reset solution chain\n",
        "        self.solution_chain = []\n",
        "\n",
        "        # Step 1: Decompose from easiest to hardest\n",
        "        print(f\"{'─'*60}\")\n",
        "        print(f\"STEP 1: Decomposing (Easiest → Hardest)\")\n",
        "        print(f\"{'─'*60}\\n\")\n",
        "\n",
        "        subproblems = self.decompose_problem(problem)\n",
        "\n",
        "        print(f\"Identified {len(subproblems)} sub-problems:\\n\")\n",
        "        for i, subprob in enumerate(subproblems, 1):\n",
        "            difficulty = [\"🟢 Easiest\", \"🟡 Easy\", \"🟠 Medium\", \"🔴 Hard\", \"🔴 Hardest\"]\n",
        "            level = difficulty[min(i-1, len(difficulty)-1)]\n",
        "            print(f\"{i}. {level}: {subprob}\")\n",
        "        print()\n",
        "\n",
        "        # Step 2-3: Solve progressively, building on previous solutions\n",
        "        print(f\"{'─'*60}\")\n",
        "        print(f\"STEP 2-3: Solving Progressively\")\n",
        "        print(f\"{'─'*60}\\n\")\n",
        "\n",
        "        for i, subproblem in enumerate(subproblems, 1):\n",
        "            print(f\"📍 Solving sub-problem {i}/{len(subproblems)}:\")\n",
        "            print(f\"   {subproblem[:70]}...\")\n",
        "\n",
        "            # Solve using previous solutions as context\n",
        "            solution = self.solve_subproblem(subproblem, self.solution_chain)\n",
        "\n",
        "            # Store in chain\n",
        "            self.solution_chain.append((subproblem, solution))\n",
        "\n",
        "            print(f\"   ✓ Solution: {solution[:100]}...\")\n",
        "\n",
        "            if i < len(subproblems):\n",
        "                print(f\"   → Will use this solution for next sub-problem\\n\")\n",
        "            else:\n",
        "                print()\n",
        "\n",
        "        # Step 4: Integrate into final solution\n",
        "        print(f\"{'─'*60}\")\n",
        "        print(f\"STEP 4: Integrating Final Solution\")\n",
        "        print(f\"{'─'*60}\\n\")\n",
        "\n",
        "        final_answer = self.integrate_final_solution(problem, self.solution_chain)\n",
        "\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"💡 FINAL ANSWER\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(final_answer)\n",
        "        print()\n",
        "\n",
        "        return final_answer"
      ],
      "metadata": {
        "id": "7EaJnIX0bW57"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Example 1: Compositional Generalization\n",
        "print(\"=\"*60)\n",
        "print(\"EXAMPLE 1: Compositional Reasoning\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent1 = LeastToMostAgent()\n",
        "agent1.solve(\n",
        "    \"If all roses are flowers, and some flowers fade quickly, and all things that fade quickly need water, \"\n",
        "    \"do some roses need water?\"\n",
        ")\n",
        "\n",
        "\n",
        "# Example 2: Math Problem (Progressive Difficulty)\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 2: Progressive Math Problem\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent2 = LeastToMostAgent()\n",
        "agent2.solve(\n",
        "    \"Calculate the compound interest on $1000 invested at 5% annual rate for 3 years, \"\n",
        "    \"compounded quarterly. Then calculate the total amount and the interest earned.\"\n",
        ")\n",
        "\n",
        "\n",
        "# Example 3: Code Synthesis\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 3: Progressive Code Building\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent3 = LeastToMostAgent()\n",
        "agent3.solve(\n",
        "    \"Write a Python function that takes a list of numbers and returns the average of only \"\n",
        "    \"the positive even numbers. Handle empty lists and edge cases.\"\n",
        ")\n",
        "\n",
        "\n",
        "# Example 4: Scientific Reasoning\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 4: Scientific Derivation\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent4 = LeastToMostAgent()\n",
        "agent4.solve(\n",
        "    \"A car accelerates from rest at 2 m/s² for 5 seconds, then maintains constant velocity for 10 seconds, \"\n",
        "    \"then decelerates at 1 m/s² until it stops. Calculate total distance traveled.\"\n",
        ")\n",
        "\n",
        "\n",
        "# Example 5: Educational Problem\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 5: Educational Math Tutoring\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent5 = LeastToMostAgent()\n",
        "agent5.solve(\n",
        "    \"Solve: (3x + 2)(2x - 1) = 0. Find all values of x. Show each step clearly.\"\n",
        ")\n",
        "\n",
        "\n",
        "# Example 6: Algorithmic Thinking\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 6: Algorithm Design\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent6 = LeastToMostAgent()\n",
        "agent6.solve(\n",
        "    \"Design an algorithm to find the longest palindromic substring in a given string. \"\n",
        "    \"Start with understanding palindromes, then build up to the full solution.\"\n",
        ")\n",
        "\n",
        "\n",
        "# Example 7: Complex Word Problem\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 7: Multi-Step Word Problem\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent7 = LeastToMostAgent()\n",
        "agent7.solve(\n",
        "    \"A store has a sale. Shirts are 25% off. You buy 3 shirts at $40 each. \"\n",
        "    \"There's an additional $10 off coupon for purchases over $100. \"\n",
        "    \"Sales tax is 8% on the final discounted price. What's the total you pay?\"\n",
        ")\n",
        "\n",
        "\n",
        "# Example 8: Logical Puzzle\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 8: Progressive Logic Puzzle\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "agent8 = LeastToMostAgent()\n",
        "agent8.solve(\n",
        "    \"In a group of 100 people, 60 like coffee, 50 like tea, and 30 like both. \"\n",
        "    \"How many like neither? How many like only coffee? How many like at least one?\"\n",
        ")\n",
        "\n",
        "\n",
        "print(\"✅ Least-to-Most Prompting Complete!\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "aa-8eZjMda0M",
        "outputId": "f593260b-2cfd-43e6-ebee-e96f2ea6c34f"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "============================================================\n",
            "EXAMPLE 1: Compositional Reasoning\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "📈 Least-to-Most Prompting\n",
            "============================================================\n",
            "Problem: If all roses are flowers, and some flowers fade quickly, and all things that fade quickly need water, do some roses need water?\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 1: Decomposing (Easiest → Hardest)\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Identified 5 sub-problems:\n",
            "\n",
            "1. 🟢 Easiest: **Basic Set Relationships:** Understand what it means when \"All A are B\". Can you visualize or represent this relationship (e.g., with a Venn diagram)?  Focus on the idea that every element of set A is also an element of set B.\n",
            "2. 🟡 Easy: **Understanding \"Some\":** Grasp the meaning of \"Some A are B\". This means at least one A is also a B, but not necessarily all of them. Visualizing this in conjunction with \"All A are B\" from the previous step is important.\n",
            "3. 🟠 Medium: **Combining \"All\" and \"Some\":** Given \"All A are B\" and \"Some B are C\", can you determine if any A *must* be C? (The answer is no.) Practice drawing examples to see when this is possible and when it isn't.\n",
            "4. 🔴 Hard: **Applying Transitivity (with caveats):** Understand the basic transitivity concept: If all X are Y and all Y are Z, then all X are Z. But be able to recognize how 'some' affects transitivity. If all X are Y, and *some* Y are Z, you can't conclude all X are Z.\n",
            "5. 🔴 Hardest: **Solving the Specific Problem:** Apply the concepts from the previous sub-problems to the specific relationships given:\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 2-3: Solving Progressively\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "📍 Solving sub-problem 1/5:\n",
            "   **Basic Set Relationships:** Understand what it means when \"All A are ...\n",
            "   ✓ Solution: Okay, here's the solution to the foundational problem, focusing on the understanding of \"All A are B...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 2/5:\n",
            "   **Understanding \"Some\":** Grasp the meaning of \"Some A are B\". This me...\n",
            "   ✓ Solution: Okay, building on the understanding of \"All A are B\", let's break down \"Some A are B\":\n",
            "\n",
            "**Understand...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 3/5:\n",
            "   **Combining \"All\" and \"Some\":** Given \"All A are B\" and \"Some B are C\"...\n",
            "   ✓ Solution: Okay, let's analyze the combined statements \"All A are B\" and \"Some B are C\" to determine if any A *...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 4/5:\n",
            "   **Applying Transitivity (with caveats):** Understand the basic transit...\n",
            "   ✓ Solution: Okay, let's break down the transitivity concept, particularly how it's affected by the inclusion of ...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 5/5:\n",
            "   **Solving the Specific Problem:** Apply the concepts from the previous...\n",
            "   ✓ Solution: Okay, I'm ready to apply the previous concepts to a specific problem. Please provide the specific re...\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 4: Integrating Final Solution\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "============================================================\n",
            "💡 FINAL ANSWER\n",
            "============================================================\n",
            "Okay, let's solve the original problem, applying all the concepts we've built up in the progressive solutions:\n",
            "\n",
            "**Original Problem:** If all roses are flowers, and some flowers fade quickly, and all things that fade quickly need water, do some roses need water?\n",
            "\n",
            "**Step 1: Define the Sets:**\n",
            "\n",
            "*   R = Roses\n",
            "*   F = Flowers\n",
            "*   Q = Things that fade quickly\n",
            "*   W = Things that need water\n",
            "\n",
            "**Step 2: Express the Relationships as \"All\" and \"Some\" Statements:**\n",
            "\n",
            "1.  All roses are flowers:  All R are F\n",
            "2.  Some flowers fade quickly: Some F are Q\n",
            "3.  All things that fade quickly need water: All Q are W\n",
            "\n",
            "**Step 3: Visualize with Venn Diagrams:**\n",
            "\n",
            "First, draw a Venn diagram representing \"All R are F\":\n",
            "\n",
            "```\n",
            "      F\n",
            "   +-------+\n",
            "   |       |\n",
            "   |   R   |\n",
            "   |       |\n",
            "   +-------+\n",
            "```\n",
            "\n",
            "Next, add \"Some F are Q\":  Since we don't know if the 'Q' overlaps with 'R' yet, we draw it so it *could* overlap, but doesn't have to.\n",
            "\n",
            "```\n",
            "      F\n",
            "   +-------+\n",
            "   |       |   +---+\n",
            "   |   R   |   | Q |\n",
            "   | +---+-+   +---+\n",
            "   | |   | |\n",
            "   | +---+-+\n",
            "   |       |\n",
            "   +-------+\n",
            "```\n",
            "\n",
            "Finally, add \"All Q are W\":\n",
            "\n",
            "```\n",
            "      F\n",
            "   +-------+\n",
            "   |       |   +-------+\n",
            "   |   R   |   |       |\n",
            "   | +---+-+   |   Q   |\n",
            "   | |   | |   |       |\n",
            "   | +---+-+   +-------+\n",
            "   |       |       |\n",
            "   +-------+-------+\n",
            "               |\n",
            "               +---+\n",
            "               | W |\n",
            "               +---+\n",
            "```\n",
            "\n",
            "**Step 4: Analyze and Draw Conclusions:**\n",
            "\n",
            "We want to know if \"Some R are W\" *must* be true.\n",
            "\n",
            "*   We know \"All R are F\".\n",
            "*   We know \"Some F are Q\".  This means there's an overlap between F and Q.  However, this overlap *might not* include any roses (R). The part of F that is Q could be entirely outside of R.\n",
            "*   We know \"All Q are W\".  This means Q is entirely contained within W.\n",
            "\n",
            "If the overlap between F and Q does *not* include any roses, then *no* roses are Q.  And since all Q are W, that means no roses are W.\n",
            "\n",
            "However, it *is possible* for the Q to overlap with both F and R. In that case, some roses would be Q, and since all Q are W, those roses would also be W.\n",
            "\n",
            "**Step 5: Final Answer:**\n",
            "\n",
            "No, it is **not necessarily true** that some roses need water. While it is *possible* that some roses need water, the given information doesn't guarantee it.  The flowers that fade quickly (Q) could be entirely different flowers than the roses (R). The overlap of Q and F might not include any R at all.\n",
            "\n",
            "**Final Answer: No.**\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 2: Progressive Math Problem\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "📈 Least-to-Most Prompting\n",
            "============================================================\n",
            "Problem: Calculate the compound interest on $1000 invested at 5% annual rate for 3 years, compounded quarterly. Then calculate the total amount and the interest earned.\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 1: Decomposing (Easiest → Hardest)\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Identified 4 sub-problems:\n",
            "\n",
            "1. 🟢 Easiest: **Calculate the Quarterly Interest Rate:**  Divide the annual interest rate by the number of compounding periods per year.  This is the easiest step as it only involves a simple division.\n",
            "2. 🟡 Easy: **Calculate the Total Number of Compounding Periods:** Multiply the number of years by the number of compounding periods per year.\n",
            "3. 🟠 Medium: **Calculate the Compound Amount:** Using the formula for compound amount, calculate the final amount after the specified number of years: `A = P (1 + r/n)^(nt)` where:\n",
            "4. 🔴 Hard: **Calculate the Interest Earned:** Subtract the principal amount from the compound amount calculated in the previous step.  This gives you the total interest earned over the investment period.\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 2-3: Solving Progressively\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "📍 Solving sub-problem 1/4:\n",
            "   **Calculate the Quarterly Interest Rate:**  Divide the annual interest...\n",
            "   ✓ Solution: ```python\n",
            "def calculate_quarterly_interest_rate(annual_interest_rate):\n",
            "  \"\"\"Calculates the quarterly...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 2/4:\n",
            "   **Calculate the Total Number of Compounding Periods:** Multiply the nu...\n",
            "   ✓ Solution: ```python\n",
            "def calculate_total_compounding_periods(years, compounding_periods_per_year):\n",
            "  \"\"\"Calcula...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 3/4:\n",
            "   **Calculate the Compound Amount:** Using the formula for compound amou...\n",
            "   ✓ Solution: ```python\n",
            "def calculate_compound_amount(principal, annual_interest_rate, years, compounding_periods_...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 4/4:\n",
            "   **Calculate the Interest Earned:** Subtract the principal amount from ...\n",
            "   ✓ Solution: ```python\n",
            "def calculate_interest_earned(principal, annual_interest_rate, years, compounding_periods_...\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 4: Integrating Final Solution\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "============================================================\n",
            "💡 FINAL ANSWER\n",
            "============================================================\n",
            "```python\n",
            "def calculate_quarterly_interest_rate(annual_interest_rate):\n",
            "  \"\"\"Calculates the quarterly interest rate from an annual interest rate.\n",
            "\n",
            "  Args:\n",
            "    annual_interest_rate: The annual interest rate (as a decimal, e.g., 0.05 for 5%).\n",
            "\n",
            "  Returns:\n",
            "    The quarterly interest rate (as a decimal).\n",
            "  \"\"\"\n",
            "  return annual_interest_rate / 4\n",
            "\n",
            "def calculate_total_compounding_periods(years, compounding_periods_per_year):\n",
            "  \"\"\"Calculates the total number of compounding periods.\n",
            "\n",
            "  Args:\n",
            "    years: The number of years.\n",
            "    compounding_periods_per_year: The number of compounding periods per year (e.g., 4 for quarterly, 12 for monthly).\n",
            "\n",
            "  Returns:\n",
            "    The total number of compounding periods.\n",
            "  \"\"\"\n",
            "  return years * compounding_periods_per_year\n",
            "\n",
            "def calculate_compound_amount(principal, annual_interest_rate, years, compounding_periods_per_year):\n",
            "  \"\"\"Calculates the compound amount (future value) of an investment.\n",
            "\n",
            "  Args:\n",
            "    principal: The initial principal amount.\n",
            "    annual_interest_rate: The annual interest rate (as a decimal, e.g., 0.05 for 5%).\n",
            "    years: The number of years.\n",
            "    compounding_periods_per_year: The number of compounding periods per year (e.g., 4 for quarterly, 12 for monthly).\n",
            "\n",
            "  Returns:\n",
            "    The compound amount (future value) after the specified number of years.\n",
            "  \"\"\"\n",
            "\n",
            "  # Calculate the quarterly interest rate\n",
            "  quarterly_interest_rate = annual_interest_rate / compounding_periods_per_year\n",
            "\n",
            "  # Calculate the total number of compounding periods\n",
            "  total_compounding_periods = years * compounding_periods_per_year\n",
            "\n",
            "  # Calculate the compound amount using the formula: A = P (1 + r/n)^(nt)\n",
            "  compound_amount = principal * (1 + quarterly_interest_rate)**total_compounding_periods\n",
            "\n",
            "  return compound_amount\n",
            "\n",
            "def calculate_interest_earned(principal, annual_interest_rate, years, compounding_periods_per_year):\n",
            "  \"\"\"Calculates the interest earned on an investment.\n",
            "\n",
            "  Args:\n",
            "    principal: The initial principal amount.\n",
            "    annual_interest_rate: The annual interest rate (as a decimal, e.g., 0.05 for 5%).\n",
            "    years: The number of years.\n",
            "    compounding_periods_per_year: The number of compounding periods per year (e.g., 4 for quarterly, 12 for monthly).\n",
            "\n",
            "  Returns:\n",
            "    The total interest earned over the investment period.\n",
            "  \"\"\"\n",
            "\n",
            "  # Calculate the compound amount using the formula: A = P (1 + r/n)^(nt)\n",
            "  compound_amount = calculate_compound_amount(principal, annual_interest_rate, years, compounding_periods_per_year)\n",
            "\n",
            "  # Calculate the interest earned by subtracting the principal from the compound amount\n",
            "  interest_earned = compound_amount - principal\n",
            "\n",
            "  return interest_earned\n",
            "\n",
            "# Given values from the problem\n",
            "principal = 1000\n",
            "annual_interest_rate = 0.05\n",
            "years = 3\n",
            "compounding_periods_per_year = 4\n",
            "\n",
            "# Calculate the compound amount\n",
            "compound_amount = calculate_compound_amount(principal, annual_interest_rate, years, compounding_periods_per_year)\n",
            "\n",
            "# Calculate the interest earned\n",
            "interest_earned = calculate_interest_earned(principal, annual_interest_rate, years, compounding_periods_per_year)\n",
            "\n",
            "# Print the results\n",
            "print(f\"Principal: ${principal}\")\n",
            "print(f\"Annual Interest Rate: {annual_interest_rate * 100}%\")\n",
            "print(f\"Years: {years}\")\n",
            "print(f\"Compounding Periods per Year: {compounding_periods_per_year}\")\n",
            "print(f\"Compound Amount: ${compound_amount:.2f}\")\n",
            "print(f\"Interest Earned: ${interest_earned:.2f}\")\n",
            "```\n",
            "\n",
            "```\n",
            "Principal: $1000\n",
            "Annual Interest Rate: 5.0%\n",
            "Years: 3\n",
            "Compounding Periods per Year: 4\n",
            "Compound Amount: $1160.75\n",
            "Interest Earned: $160.75\n",
            "```\n",
            "\n",
            "**Final Answer:**\n",
            "\n",
            "*   **Compound Amount:** \\$1160.75\n",
            "*   **Interest Earned:** \\$160.75\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 3: Progressive Code Building\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "📈 Least-to-Most Prompting\n",
            "============================================================\n",
            "Problem: Write a Python function that takes a list of numbers and returns the average of only the positive even numbers. Handle empty lists and edge cases.\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 1: Decomposing (Easiest → Hardest)\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Identified 6 sub-problems:\n",
            "\n",
            "1. 🟢 Easiest: **Sum of Numbers in a List:** Write a function that takes a list of numbers and returns the sum of all the numbers in the list. This helps establish basic list iteration.\n",
            "2. 🟡 Easy: **Identify Even Numbers:**  Write a function that takes a list of numbers and returns a new list containing only the even numbers from the original list. This introduces the concept of filtering based on a condition.\n",
            "3. 🟠 Medium: **Identify Positive Numbers:** Write a function that takes a list of numbers and returns a new list containing only the positive numbers from the original list. This introduces the concept of filtering based on a different condition.\n",
            "4. 🔴 Hard: **Combined Filtering (Positive and Even):** Write a function that takes a list of numbers and returns a new list containing only the positive *and* even numbers. This combines the logic from the previous two sub-problems.\n",
            "5. 🔴 Hardest: **Average of a List of Numbers:** Write a function that takes a list of numbers and returns the average of the numbers. Handle the case where the list is empty (return 0). This builds upon the sum and introduces the division for averaging.\n",
            "6. 🔴 Hardest: **Final Solution (Positive Even Average):** Write a function that takes a list of numbers, filters it to get only positive even numbers, and then returns the average of those numbers. Handle the cases where the input list is empty or there are no positive even numbers (return 0).  This ties all the previous sub-problems together to solve the original problem.\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 2-3: Solving Progressively\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "📍 Solving sub-problem 1/6:\n",
            "   **Sum of Numbers in a List:** Write a function that takes a list of nu...\n",
            "   ✓ Solution: ```python\n",
            "def sum_of_numbers(numbers):\n",
            "  \"\"\"\n",
            "  Calculates the sum of all numbers in a list.\n",
            "\n",
            "  Args:...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 2/6:\n",
            "   **Identify Even Numbers:**  Write a function that takes a list of numb...\n",
            "   ✓ Solution: ```python\n",
            "def identify_even_numbers(numbers):\n",
            "  \"\"\"\n",
            "  Identifies and returns a new list containing o...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 3/6:\n",
            "   **Identify Positive Numbers:** Write a function that takes a list of n...\n",
            "   ✓ Solution: ```python\n",
            "def identify_positive_numbers(numbers):\n",
            "  \"\"\"\n",
            "  Identifies and returns a new list containi...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 4/6:\n",
            "   **Combined Filtering (Positive and Even):** Write a function that take...\n",
            "   ✓ Solution: ```python\n",
            "def combined_filtering(numbers):\n",
            "  \"\"\"\n",
            "  Identifies and returns a new list containing only...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 5/6:\n",
            "   **Average of a List of Numbers:** Write a function that takes a list o...\n",
            "   ✓ Solution: ```python\n",
            "def average_of_numbers(numbers):\n",
            "  \"\"\"\n",
            "  Calculates the average of a list of numbers.\n",
            "\n",
            "  A...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 6/6:\n",
            "   **Final Solution (Positive Even Average):** Write a function that take...\n",
            "   ✓ Solution: ```python\n",
            "def positive_even_average(numbers):\n",
            "  \"\"\"\n",
            "  Calculates the average of positive even number...\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 4: Integrating Final Solution\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "============================================================\n",
            "💡 FINAL ANSWER\n",
            "============================================================\n",
            "```python\n",
            "def positive_even_average(numbers):\n",
            "  \"\"\"\n",
            "  Calculates the average of positive even numbers in a list.\n",
            "\n",
            "  Args:\n",
            "    numbers: A list of numbers (integers or floats).\n",
            "\n",
            "  Returns:\n",
            "    The average of the positive even numbers in the list.\n",
            "    Returns 0 if the list is empty or contains no positive even numbers.\n",
            "  \"\"\"\n",
            "  positive_and_even_numbers = []  # Initialize an empty list to store positive and even numbers\n",
            "  for number in numbers:\n",
            "    if number > 0 and number % 2 == 0:  # Check if the number is positive AND even\n",
            "      positive_and_even_numbers.append(number)  # If both, add it to the list\n",
            "\n",
            "  if not positive_and_even_numbers:  # Check if the list of positive even numbers is empty\n",
            "    return 0  # Return 0 if the list is empty\n",
            "\n",
            "  total = 0  # Initialize the sum to 0\n",
            "  for number in positive_and_even_numbers:\n",
            "    total += number  # Add each number in the list to the total\n",
            "\n",
            "  average = total / len(positive_and_even_numbers)  # Calculate the average\n",
            "  return average\n",
            "\n",
            "# Example usage:\n",
            "my_list = [-4, -2, -1, 0, 1, 2, 4, 5]\n",
            "average = positive_even_average(my_list)\n",
            "print(f\"The average of positive even numbers is: {average}\")\n",
            "\n",
            "mixed_list = [-3, -1, 1, 3, 5]\n",
            "average_mixed = positive_even_average(mixed_list)\n",
            "print(f\"The average of positive even numbers in the mixed list is: {average_mixed}\")\n",
            "\n",
            "empty_list = []\n",
            "average_empty = positive_even_average(empty_list)\n",
            "print(f\"The average of positive even numbers in the empty list is: {average_empty}\")\n",
            "\n",
            "list_with_no_positive_even = [-1, -2, -3, -5]\n",
            "average_no_pos_even = positive_even_average(list_with_no_positive_even)\n",
            "print(f\"The average of positive even numbers in the list with no positive even numbers is: {average_no_pos_even}\")\n",
            "```\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 4: Scientific Derivation\n",
            "============================================================\n",
            "\n",
            "============================================================\n",
            "📈 Least-to-Most Prompting\n",
            "============================================================\n",
            "Problem: A car accelerates from rest at 2 m/s² for 5 seconds, then maintains constant velocity for 10 seconds, then decelerates at 1 m/s² until it stops. Calculate total distance traveled.\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 1: Decomposing (Easiest → Hardest)\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "Identified 6 sub-problems:\n",
            "\n",
            "1. 🟢 Easiest: **Calculate the final velocity during acceleration phase:**\n",
            "2. 🟡 Easy: **Calculate the distance traveled during the acceleration phase:**\n",
            "3. 🟠 Medium: **Calculate the distance traveled during the constant velocity phase:**\n",
            "4. 🔴 Hard: **Calculate the time it takes to decelerate to a stop:**\n",
            "5. 🔴 Hardest: **Calculate the distance traveled during the deceleration phase:**\n",
            "6. 🔴 Hardest: **Calculate the total distance:**\n",
            "\n",
            "────────────────────────────────────────────────────────────\n",
            "STEP 2-3: Solving Progressively\n",
            "────────────────────────────────────────────────────────────\n",
            "\n",
            "📍 Solving sub-problem 1/6:\n",
            "   **Calculate the final velocity during acceleration phase:**...\n",
            "   ✓ Solution: Okay, here's the solution for calculating the final velocity during an acceleration phase, assuming ...\n",
            "   → Will use this solution for next sub-problem\n",
            "\n",
            "📍 Solving sub-problem 2/6:\n",
            "   **Calculate the distance traveled during the acceleration phase:**...\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "YxeH0lANdeuM"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}